import axios from 'axios'
import JSBridge from './JSBridge'
import {
  Loading
} from 'element-ui'
import {
  Toast
} from 'vant'

axios.defaults.timeout = 5000
axios.defaults.baseURL = process.env.HOST
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let loadingInstance = null
const jsBridge = JSBridge.getInstance()

axios.interceptors.request.use(config => {
  if (!config.headers.hasOwnProperty('FastMode')) {
    loadingInstance = Loading.service({
      fullscreen: true
    })
  }

  if (config.headers.hasOwnProperty('AuthShare')) {
    return config
  }
  // todo
  // 从这里拿到待请求的地址，判断是否是share的，如果是返回一个公用token，或者别的啥值
  // todo
  return new Promise((resolve, reject) => {
    jsBridge.getAccessToken((token) => {
      config.headers.Authorization = 'Bearer ' + token
      return resolve(config)
    })
  })
  // return retry
}, error => {
  console.log(error)
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  loadingInstance !== null && loadingInstance.close()
  // Do something with response data
  if (response.data.code !== 200) {
    if (response.data.code === 403) {
      jsBridge.goToLoginPage(null, () => {})
    }
    Toast(response.data.msg)
    console.log(response)
    return Promise.reject(response.data.msg)
  }
  return response.data
}, error => {
  console.log('error -> : ', error)
  loadingInstance !== null && loadingInstance.close()
  // Do something with response error
  if (typeof error === 'string' && error.constructor === String) {
    Toast(error)
  } else if (typeof error === 'object' && error.constructor === Object && error.response) {
    Toast('网络请求超时或者页面内部错误')
  } else {
    // 断网了
    Toast('网络已断开、网络信号弱或路由器故障，建议重新 设置网络')
  }
  return Promise.reject(error)
})

export default axios
